package com.web.music.portal.mvc;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.servlet.mvc.SimpleFormController;
import com.web.music.common.*;
import com.web.music.interfaces.GenreService;
import com.web.music.interfaces.SecurityController;
import com.web.music.model.Genre;

public class GenreFormController extends SimpleFormController {

	private GenreService genreService;
	private SecurityController securityController;
	
	public GenreFormController() {
		setCommandClass(Genre.class);
		setSessionForm(true);
	}
	
	@Override
	protected Object formBackingObject(HttpServletRequest request) {		
		Genre genre = new Genre();
		genre.setCreatedBy(securityController.getSessionUser(request));		
		// execute the following code only when going to display a form
		if (!isFormSubmission(request)){	
			String idString = request.getParameter("id");
			if (idString != null && !idString.equals("")) {
				long id = Long.parseLong(request.getParameter("id"));
				genre = genreService.getById(id);
			}			
		}		
		securityController.updateSecurityStatus(request, genre);
		return genre;		
	}

	@Override
	public void doSubmitAction(Object object){
		Genre genre = (Genre)object;	
		try {
			if (genre.getUpdateGranted()){ //Check if somebody does not "hack" url
				genreService.save(genre);
			}
		}
		catch (javax.persistence.EntityExistsException e){
			throw new MusicException("Genre "+genre.getName()+" already exists");
		}
	}

	public GenreService getGenreService() {
		return genreService;
	}

	public void setGenreService(GenreService genreService) {
		this.genreService = genreService;
	}
	public SecurityController getSecurityController() {
		return securityController;
	}

	public void setSecurityController(
			SecurityController securityController) {
		this.securityController = securityController;
	}	
}
